<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width: 700px;">
        <el-form :model="addAssetsAloneForm" ref="addBaseAddressRef" :rules="addAssetsAlonerules">
            <el-form-item label="归口单位" :label-width="formLabelWidth" prop="company">
                <!-- <el-input v-model="addAssetsAloneForm.company" autocomplete="off" :disabled="title == '修改资产'"
                    ref="company" placeholder="请填写归口单位"></el-input> -->
                <el-select v-model="addAssetsAloneForm.company" style="width: 100%;" class="m-2 selest_11"
                    placeholder="请选择归口单位">
                    <el-option v-for="(item, index) in schoolArr" :key="index" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="资产名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="addAssetsAloneForm.name" autocomplete="off" ref="name" :disabled="title == '修改资产'"
                    placeholder="请填写资产名称"></el-input>
            </el-form-item>
            <el-form-item label="型号" :label-width="formLabelWidth" prop="code">
                <el-input v-model="addAssetsAloneForm.model" autocomplete="off" ref="code" :disabled="title == '修改资产'"
                    placeholder="请填写型号"></el-input>
            </el-form-item>
            <el-form-item label="单价" :label-width="formLabelWidth" prop="price">
                <el-input v-model="addAssetsAloneForm.price" autocomplete="off" ref="price" :disabled="title == '修改资产'"
                    placeholder="请填写单价"></el-input>
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth" prop="amount">
                <el-input v-model="addAssetsAloneForm.amount" autocomplete="off" ref="amount"
                    :disabled="title == '修改资产'" placeholder="请填写数量"></el-input>
            </el-form-item>
            <el-form-item label="金额" :label-width="formLabelWidth" prop="money">
                <el-input v-model="addAssetsAloneForm.money" autocomplete="off" ref="money" :disabled="title == '修改资产'"
                    placeholder="请填写金额"></el-input>
            </el-form-item>
            <el-form-item label="管理人" :label-width="formLabelWidth" prop="manager">
                <!-- <el-input v-model="addAssetsAloneForm.manager" autocomplete="off" ref="manager"
                    :disabled="title == '修改资产'" placeholder="请填写管理人"></el-input> -->
                <el-select v-model="addAssetsAloneForm.managerId" filterable :filter-method="serachTeacher"
                    placeholder="请选择管理人 " style="width:100%" clearable @change="handleChangeCascader1">
                    <el-option v-for="item in teacherList" :key="item.id" :label="item.name"
                        :value="item.teacherNumber" />
                </el-select>
            </el-form-item>
            <el-form-item label="使用部门" :label-width="formLabelWidth" prop="department">
                <!-- <el-input v-model="addAssetsAloneForm.department" autocomplete="off" ref="categoryCode"
                    placeholder="请填写使用部门"></el-input> -->
                <el-select v-model="addAssetsAloneForm.department" filterable placeholder="请选择盘点人 " style="width:100%"
                    clearable @change="handleChangedepartment">
                    <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="使用人" :label-width="formLabelWidth" prop="useTeacher">
                <el-select v-model="addAssetsAloneForm.useTeacher" filterable :filter-method="serachTeacher"
                    placeholder="请选择使用人 " style="width:100%" clearable @change="handleChangeCascader">
                    <el-option v-for="item in teacherList" :key="item.id" :label="item.name"
                        :value="item.teacherNumber" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="存放校区" :label-width="formLabelWidth" prop="campus"> 
                <el-select v-model="addAssetsAloneForm.campus" style="width: 100%;" class="m-2 selest_11"
                    placeholder="请选择归口单位">
                    <el-option v-for="(item, index) in schoolData" :key="index" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="存放地点" :label-width="formLabelWidth" prop="place">
                <!-- <el-input v-model="addAssetsAloneForm.place" autocomplete="off" ref="place"
                    placeholder="请填写存放地点"></el-input> -->
                <el-cascader :placeholder="getStoreAdress(addAssetsAloneForm.place)" :options="addresslist" filterable
                    v-model="addAssetsAloneForm.place" @change="handleChangePlace" style="width: 100%;" />
            </el-form-item>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel()">取消</el-button>
                <el-button type="primary" @click="save()">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessageBox, ElMessage, ElForm } from "element-plus";
import { vxRule } from "@/utils/validator";
import { API_BASE_NAME, API_BASE_NAME1, API_BASE_NAME3, API_BASE_NAME2, } from '../../constants';

export default {
    name: "AddFaAssets",
    components: { ElForm, ElMessage, ElMessageBox },
    data() {
        return {
            dialogFormVisible: ref(false),
            formLabelWidth: "120px",
            title: "",
            personnelType: "",
            rowIndex: '',
            columnIndex: '',
            parentId: '',
            excelAccept: '.xls,.xlsx',
            teacherList: [],
            departmentList: [],
            addresslist: [],
            user: {},
            schoolArr: [
                {
                    value: API_BASE_NAME,
                    label: API_BASE_NAME,
                },
                {
                    value: API_BASE_NAME1,
                    label: API_BASE_NAME1,
                },
            ],
            schoolData: [
                {
                    value: 1,
                    label: API_BASE_NAME2,
                },
                {
                    value: 2,
                    label: API_BASE_NAME3,
                },
            ],
            addAssetsAloneForm: {
                name: "",
                code: "",
                oldCode: "",
                category: "",
                categoryCode: "",
                standards: "",
                model: "",
                price: "",
                amount: "",
                money: "",
                department: "",
                managerDepartment: "",
                manager: "",
                managerId: "",
                place: "",
                useTeacher: "",
                useTeacherNumber: "",
                // department: "",
                departmentId: "",
                company: "",
                campus: '',
            },
            addAssetsAlonerules: {
                name: vxRule(true, null, "blur"),
                price: vxRule(true, null, "blur"),
                amount: vxRule(true, null, "blur"),
                money: vxRule(true, null, "blur"),
                place: vxRule(true, null, "blur"),
                manager: vxRule(true, null, "blur"),
                useTeacher: vxRule(true, null, "blur"),
                department: vxRule(true, null, "blur"),
                company: vxRule(true, null, "blur"),
                campus: vxRule(true, null, "blur"),
            },
        };
    },
    mounted() {
        this.user = JSON.parse(sessionStorage.getItem("user"))
        this.getAddressList()
    },
    methods: {
        closeDialog() {
            this.dialogFormVisible = false;
            this.clear()
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear()
        },
        getStoreAdress(str) {
            return str ? str : '请选择存放地点'
        },
        getBaseTeacherList() {
            httpService(
                "/javaApi/baseTeacher/list/1/10000",
                {},
                "get"
            ).then((data) => {
                this.teacherList = data.list;
            });
        },
        getBaseDepartment() {
            httpService(
                "/javaApi/baseDepartment/list/1/100",
                {},
                "get"
            ).then((data) => {
                this.departmentList = data.list;
            });
        },
        handleChangeCascader(value) {
            let arr = []
            if (this.teacherList) {
                arr = this.teacherList.filter(item => item.teacherNumber == value)
            }
            this.addAssetsAloneForm.useTeacher = arr[0].name
            this.addAssetsAloneForm.useTeacherNumber = value
        },
        handleChangeCascader1(value) {
            let arr = []
            if (this.teacherList) {
                arr = this.teacherList.filter(item => item.teacherNumber == value)
            }
            this.addAssetsAloneForm.manager = arr[0].name
        },
        handleChangedepartment(value) {
            let arr = []
            if (this.departmentList) {
                arr = this.departmentList.filter(item => item.id == value)
            }
            this.addAssetsAloneForm.department = arr[0].name
            this.addAssetsAloneForm.departmentId = value
        },
        handleChangePlace(value) {
            this.addAssetsAloneForm.place = value.join("-")
        },
        serachTeacher(value) {
            console.log(value);
            httpService(
                "/javaApi/baseTeacher/list/1/10000",
                { name: value },
                "get"
            ).then((data) => {
                this.teacherList = data.list;
            });
        },
        clear() {
            this.dialogFormVisible = false;
        },
        getAddressList() {
            httpService(
                "/javaApi/baseAddress/list/1/10000",
                {
                    campus: 1,
                }, "get"
            ).then((data) => {
                if (data.list) {
                    data.list.forEach(item => item.children = []);
                }

                const arr = data.list.map(item => {
                    const { alias, ...rest } = item;
                    return { label: alias, value: alias, ...rest };
                });

                this.addresslist = this.buildTree(arr)
            });
        },
        buildTree(items) {
            const idMap = {};
            const tree = [];
            items.forEach(item => {
                idMap[item.id] = { ...item, children: [] };
            });
            items.forEach(item => {
                const parentId = item.parentId;
                const currentNode = idMap[item.id];

                if (parentId === 0) {
                    tree.push(currentNode);
                } else {
                    const parent = idMap[parentId];
                    if (parent) {
                        parent.children.push(currentNode);
                    }
                }
            });
            
            if (tree.length > 0) {
                return tree[0].children
            }
            // if (this.user.campus == 1) {
            //     return tree[1].children
            // } else if (this.user.campus == 2) {
            //     return tree[0].children
            // }

            // return [...tree[0].children]
        },

        save() {
            // console.log(this.addAssetsAloneForm.campus, this.addAssetsAloneForm.place,this.addAssetsAloneForm.useTeacher, this.addAssetsAloneForm.useTeacherNumber, this.addAssetsAloneForm.department, this.addAssetsAloneForm.departmentId);
            this.$refs.addBaseAddressRef.validate((valid) => {
                if (valid) {
                    let params = new FormData()
                    params.append('company', this.addAssetsAloneForm.company)
                    params.append('name', this.addAssetsAloneForm.name)
                    params.append('model', this.addAssetsAloneForm.model)
                    params.append('price', this.addAssetsAloneForm.price)
                    params.append('amount', this.addAssetsAloneForm.amount)
                    params.append('money', this.addAssetsAloneForm.money)
                    params.append('place', this.addAssetsAloneForm.place)
                    params.append('manager', this.addAssetsAloneForm.manager)
                    params.append('useTeacher', this.addAssetsAloneForm.useTeacher)
                    params.append('useTeacherNumber', this.addAssetsAloneForm.useTeacherNumber)
                    params.append('departmentId', this.addAssetsAloneForm.departmentId)
                    params.append('department', this.addAssetsAloneForm.department)

                    if (this.parentId) {
                        params.append("id", this.parentId);
                        httpService("/javaApi/faSubList/edit", params, "post").then(
                            (data) => {
                                console.log(data);
                                if (data.code == 200) {
                                    ElMessage.success('修改成功');
                                    this.clear()
                                    //刷新父组件的数据
                                    this.$parent.getFaProjectList();
                                } else {
                                    ElMessage.error('修改失败');
                                }
                            }
                        );
                    } else {
                        httpService("/javaApi/faSubList/add", params, "post").then(
                            (data) => {
                                console.log(data);
                                if (data.code == 200) {
                                    ElMessage.success('添加成功');
                                    this.clear()
                                    //刷新父组件的数据
                                    this.$parent.getFaProjectList();
                                } else {
                                    ElMessage.error('添加失败');
                                }
                            }
                        );
                    }
                } else {
                    return false;
                }
            });

        },
    },
};
</script>
<style>
.el-dialog {
    width: 80%;
}

.selest_11 {
    width: 190px;
}

.el-upload button {
    width: 190px;
}

.el-dialog__header {
    padding: var(--el-dialog-padding-primary);
    padding-bottom: 10px;
    border-bottom: 1px solid #dedede;
    margin-bottom: 15px;
}
</style>